package com.yuanjun.product.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yuanjun.product.dao.*;
import com.yuanjun.product.entity.*;
import com.yuanjun.product.service.ProductService;
import com.yuanjun.product.utils.DateUtil;
import com.yuanjun.product.vo.base.BaseResult;
import com.yuanjun.product.vo.common.Const;
import com.yuanjun.product.vo.req.*;
import com.yuanjun.product.dao.JczProductMapper;
import com.yuanjun.product.entity.JczProduct;
import com.yuanjun.product.service.ProductService;
import com.yuanjun.product.vo.base.BaseResult;
import com.yuanjun.product.vo.base.PageVo;
import com.yuanjun.product.vo.common.Const;
import com.yuanjun.product.vo.resp.RespConfirmOrderVo;
import com.yuanjun.product.vo.resp.RespOwnOrderListVo;
import com.yuanjun.product.vo.resp.RespProductDetailVo;
import com.yuanjun.product.vo.resp.RespProductListVo;
import com.yuanjuntech.modules.notify.interfaces.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Value("${spring.profiles.active}")
    private String env;
    @Value("${order_notice_code}")
    private int ORDERNOTICE;
    @Value("${business_mobile}")
    private String MOBILE;
    @Resource
    JczOrderMapper jczOrderMapper;
    @Resource
    private JczProductPictureMapper jczProductPictureMapper;
    @Resource
    private JczProductMapper jczProductMapper;
    @Resource
    private  JczOrderProductMapper jczOrderProductMapper;
    @Reference(version = "1.0.0")
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public BaseResult productList(ReqProductListVo reqProductListVo) {
        Map<String, Object> params = new HashMap();
        params.put("pageSize", reqProductListVo.getPageSize());
        params.put("pageStart", (reqProductListVo.getCurPage() - 1) * reqProductListVo.getPageSize());
        params.put("productName",reqProductListVo.getProductName());
        List<RespProductListVo> productList = jczProductMapper.getProductList(params);
        Long totalCount = jczProductMapper.getProductListCount(params);
        //设置回参
        PageVo<RespProductListVo> pageVo = new PageVo<>();
        pageVo.setCurPage(reqProductListVo.getCurPage());
        pageVo.setPageSize(reqProductListVo.getPageSize());
        pageVo.setPageStart((reqProductListVo.getCurPage() - 1) * reqProductListVo.getPageSize());
        pageVo.setList(productList);
        pageVo.setTotalCount(totalCount);
        return BaseResult.createOk(pageVo);
    }

    @Override
    public BaseResult productDetail(ReqProductDetailVo param) {
        RespProductDetailVo respProductDetailVo = new RespProductDetailVo();
        JczProduct product = jczProductMapper.selectByPrimaryKey(param.getProductId());
        JczProductPictureExample example = new JczProductPictureExample();
        example.createCriteria().andProductIdEqualTo(param.getProductId()).andDeleteFlagEqualTo((byte) 0);
        List<JczProductPicture> jczProductPictures = jczProductPictureMapper.selectByExample(example);
        if (product != null && jczProductPictures != null && jczProductPictures.size() > 0) {
            List<String> pictures = jczProductPictures.stream().map(JczProductPicture->JczProductPicture.getPictureUrl()).collect(Collectors.toList());
            BeanUtils.copyProperties(product, respProductDetailVo);
            respProductDetailVo.setPictureUrl(pictures);
            return BaseResult.createOk(respProductDetailVo);
        } else {
            return BaseResult.createFail(Const.HttpRespCode.INTERNAL_SERVER_ERROR, "服务器异常请联系管理员。");
        }
    }

    @Override
    public BaseResult makeOrder(JczUser user, ReqMakeOrderVo param) {
        JczProduct product = jczProductMapper.selectByPrimaryKey(param.getProductId());
        BigDecimal totalIncome = product.getPrice().multiply(new BigDecimal(param.getPayCount())).setScale(2, BigDecimal.ROUND_HALF_UP);
        JczOrder order = new JczOrder();
        order.setUserId(user.getId());
        // 订单初始化
        order.setStatus((byte) 0);
        order.setTotalCount(param.getPayCount());
        order.setTotalIncome(totalIncome);
        String orderNum =  buildOrderNum();
        order.setOrderNumber(orderNum);
        jczOrderMapper.insertSelective(order);
        // 插入订单产品关系表
        JczOrderProduct orderProduct = new JczOrderProduct();
        orderProduct.setOrderId(order.getId());
        orderProduct.setProductId(param.getProductId());
        orderProduct.setCount(param.getPayCount());
        orderProduct.setIncome(totalIncome);
        jczOrderProductMapper.insertSelective(orderProduct);
        return BaseResult.createOk(order.getId());
    }

    @Override
    public BaseResult OrderList(ReqConfirmOrderVo param) {
        RespConfirmOrderVo respConfirmOrderVo = jczOrderMapper.getOrderList(param.getOrderId());
        return BaseResult.createOk(respConfirmOrderVo);
    }

    @Override
    public BaseResult ownOrderList(JczUser user, ReqOwnOrderListVo reqOwnOrderListVo) {
        Map<String, Object> params = new HashMap();
        params.put("pageSize", reqOwnOrderListVo.getPageSize());
        params.put("pageStart", (reqOwnOrderListVo.getCurPage() - 1) * reqOwnOrderListVo.getPageSize());
        params.put("userId", user.getId());
        params.put("orderId", reqOwnOrderListVo.getOrderId());
        List<RespOwnOrderListVo> respOwnOrderListVos = jczOrderMapper.ownOrderList(params);
        Long totalCount = jczOrderMapper.ownOrderListCount(params);
        //设置回参
        PageVo<RespOwnOrderListVo> pageVo = new PageVo<>();
        pageVo.setCurPage(reqOwnOrderListVo.getCurPage());
        pageVo.setPageSize(reqOwnOrderListVo.getPageSize());
        pageVo.setPageStart((reqOwnOrderListVo.getCurPage() - 1) * reqOwnOrderListVo.getPageSize());
        pageVo.setList(respOwnOrderListVos);
        pageVo.setTotalCount(totalCount);
        return BaseResult.createOk(pageVo);
    }

    /**
     * 完成付款接口
     *
     * @param reqEndPaymentVo
     * @return
     */
    @Override
    public BaseResult endPayment(ReqEndPaymentVo reqEndPaymentVo) {
        JczOrder jczOrder = jczOrderMapper.selectByPrimaryKey(reqEndPaymentVo.getOrderId());
        if (jczOrder == null || jczOrder.getOrderNumber() == null) {
            return BaseResult.createFail(Const.HttpRespCode.INCOMPATIBLE_CONDITION, "订单不存在,联系管理员");
        }
        jczOrder.setPayType(reqEndPaymentVo.getPayType());
        jczOrder.setPayTime(new Date());
        jczOrder.setTotalIncome(reqEndPaymentVo.getTotalIncome());
        jczOrder.setStatus((byte)2);
        jczOrderMapper.updateByPrimaryKeySelective(jczOrder);
        // 获取订单号 发送短信给商家
        String orderNumber = jczOrder.getOrderNumber();
        if ("release".equals(env)) {
            smsService.sendCustomerPhoneCreateOrder(MOBILE, orderNumber, ORDERNOTICE, null);
        }
        return BaseResult.createOk("ok");
    }

    /**
     * 订单表存收货地址id
     * @param reqOrderAddress
     * @return
     */
    @Override
    public BaseResult orderAddress(ReqOrderAddress reqOrderAddress) {
        JczOrderExample jczOrderExample=new JczOrderExample();
        jczOrderExample.createCriteria().andIdEqualTo(reqOrderAddress.getOrderId()).andDeleteFlagEqualTo(new Byte("0"));
        JczOrder jczOrder=jczOrderMapper.selectByExample(jczOrderExample).get(0);
        jczOrder.setAddressId(reqOrderAddress.getAddressId());
        jczOrderMapper.updateByPrimaryKey(jczOrder);
        return BaseResult.createOk("成功");
    }

    public static String buildOrderNum(){
        String code = "JCZ" + DateUtil.getDateFormat(new Date(), DateUtil.JYyyyyMMdd)
                + new Random().nextInt(10)
                + new Random().nextInt(10)
                + new Random().nextInt(10)
                + new Random().nextInt(10);
        return code;
    }
}
